#include"spinlock.h"
#include<iostream>
#include<vector>
#include<thread>
using namespace std;
spinlock sl;
int shared_count = 0;

//共享计数器
void countr(int iteration)
{
	for (int i = 0; i < iteration; i++)
	{
		sl.Lock();

		shared_count++;

		sl.UnLock();
	}
}

void increment_with_try_lock(int iteration)
{
	for (int i = 0; i < iteration;)
	{
		//非阻塞
		if (sl.try_lock())
		{
			//成功获取锁
			shared_count++;
			sl.UnLock();
			++i;
		}
		else{}
	}
}
int main()
{
	const int num = 4;//线程数量
	const int iteration_per_threads = 100000;//每个县城迭代的次数
	vector<thread>threads;
	cout << "启动线程" << endl;
	for (int i = 0; i < num; i++)
	{
		threads.emplace_back(increment_with_try_lock, iteration_per_threads);
	}

	//等待所有线程完成
	for (auto &th :threads)
	{
		th.join();
	}

	//结果
	cout << " expected value: " << num * iteration_per_threads << endl;
	cout << " actuall value" << shared_count << endl;

	if (shared_count == num * iteration_per_threads)
	{
		cout << "success: counter is correct" << endl;
	}
	else
	{
		cout << "error: counter is incorrect" << endl;
	}
	return 0;
}